package com.zhlq.filter;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import com.zhlq.core.service.ProjectService;
import com.zhlq.util.ConfigUtil;
import com.zhlq.util.SerializeUtil;
import com.zhlq.util.SpringContext;

/**
 * 异常捕捉过滤器
 */
public class ExceptionCatchFilter implements Filter {
	
	private ProjectService projectService;

	/**
	 * 销毁处理
	 */
	public void destroy() {
		// 不需要处理
	}

	/**
	 * 转发前处理
	 */
	public void doFilter(ServletRequest request, ServletResponse response, 
			FilterChain chain) throws IOException, ServletException {
		try {
			chain.doFilter(request, response);
		} catch (Exception e) {
			e.printStackTrace();
			com.zhlq.exception.bean.Exception exception = new com.zhlq.exception.bean.Exception();
			exception.setName(e.getClass().getName());
			exception.setMsg(e.getMessage());
			Date date = new Date();
			String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(date);
			String path = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss.SSS").format(date);
			exception.setTime(time);
			exception.setPath(path);
			path = ConfigUtil.get("serializeRoot")+File.separator+path;
			SerializeUtil.write(exception, path);
			projectService.create(exception);
			System.out.println("捕捉需要处理的异常！");
		}
	}

	/**
	 * 初始化处理
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		projectService = (ProjectService) SpringContext.getBean("projectService");
	}

}
